/**
 * API配置管理器
 * 统一管理API基础配置、环境变量和全局设置
 */

/**
 * 环境类型枚举
 */
export enum Environment {
  DEVELOPMENT = 'development',
  TEST = 'test',
  PRODUCTION = 'production',
}

/**
 * API配置接口
 */
export interface ApiConfig {
  /** API基础URL */
  baseURL: string;
  /** 请求超时时间（毫秒） */
  timeout: number;
  /** 是否启用Mock数据 */
  enableMock: boolean;
  /** 是否启用请求日志 */
  enableLogging: boolean;
  /** 是否启用错误处理 */
  enableErrorHandler: boolean;
  /** 是否启用重试机制 */
  enableRetry: boolean;
  /** 重试次数 */
  retryCount: number;
  /** 重试延迟（毫秒） */
  retryDelay: number;
  /** 是否启用加载状态 */
  enableLoading: boolean;
  /** 请求头配置 */
  headers: Record<string, string>;
}

/**
 * API端点配置
 */
export interface ApiEndpoints {
  /** 商品服务端点 */
  products: {
    base: string;
    list: string;
    detail: string;
    create: string;
    update: string;
    delete: string;
    status: string;
    search: string;
    stats: string;
    favorites: string;
  };
  /** 用户服务端点 */
  users: {
    base: string;
    login: string;
    logout: string;
    profile: string;
    register: string;
  };
  /** 文件服务端点 */
  files: {
    base: string;
    upload: string;
    download: string;
  };
}

/**
 * API配置管理器类
 */
export class ApiConfigManager {
  private static instance: ApiConfigManager;
  private config: ApiConfig;
  private endpoints: ApiEndpoints;

  private constructor() {
    this.config = this.getDefaultConfig();
    this.endpoints = this.getDefaultEndpoints();
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): ApiConfigManager {
    if (!ApiConfigManager.instance) {
      ApiConfigManager.instance = new ApiConfigManager();
    }
    return ApiConfigManager.instance;
  }

  /**
   * 获取默认配置
   */
  private getDefaultConfig(): ApiConfig {
    const environment = this.getCurrentEnvironment();
    const isDevelopment = environment === Environment.DEVELOPMENT;

    return {
      baseURL: this.getBaseURL(environment),
      timeout: 15000,
      enableMock: isDevelopment,
      enableLogging: isDevelopment,
      enableErrorHandler: true,
      enableRetry: true,
      retryCount: 3,
      retryDelay: 1000,
      enableLoading: true,
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
      },
    };
  }

  /**
   * 获取默认端点配置
   */
  private getDefaultEndpoints(): ApiEndpoints {
    return {
      products: {
        base: '/api/products',
        list: '/list',
        detail: '/detail',
        create: '/create',
        update: '/update',
        delete: '/delete',
        status: '/status',
        search: '/search',
        stats: '/stats',
        favorites: '/favorites',
      },
      users: {
        base: '/api/users',
        login: '/login',
        logout: '/logout',
        profile: '/profile',
        register: '/register',
      },
      files: {
        base: '/api/files',
        upload: '/upload',
        download: '/download',
      },
    };
  }

  /**
   * 获取当前环境
   */
  private getCurrentEnvironment(): Environment {
    if (typeof process !== 'undefined' && process.env) {
      const env = process.env.NODE_ENV;
      if (env === Environment.DEVELOPMENT) return Environment.DEVELOPMENT;
      if (env === Environment.TEST) return Environment.TEST;
      if (env === Environment.PRODUCTION) return Environment.PRODUCTION;
    }

    // 默认开发环境
    return Environment.DEVELOPMENT;
  }

  /**
   * 根据环境获取基础URL
   */
  private getBaseURL(environment: Environment): string {
    const baseURLs = {
      [Environment.DEVELOPMENT]: 'http://localhost:8000/api',
      [Environment.TEST]: 'https://test-api.campus-trade.com/api',
      [Environment.PRODUCTION]: 'https://api.campus-trade.com/api',
    };

    return baseURLs[environment] || baseURLs[Environment.DEVELOPMENT];
  }

  /**
   * 获取完整配置
   */
  public getConfig(): ApiConfig {
    return { ...this.config };
  }

  /**
   * 更新配置
   */
  public updateConfig(updates: Partial<ApiConfig>): void {
    this.config = { ...this.config, ...updates };
    
    // 记录配置变更
    if (process.env.NODE_ENV === 'development') {
      console.log('⚙️ [ApiConfig] 配置已更新:', updates);
    }
  }

  /**
   * 获取端点配置
   */
  public getEndpoints(): ApiEndpoints {
    return { ...this.endpoints };
  }

  /**
   * 根据环境动态配置
   */
  public configureForEnvironment(environment: Environment): void {
    const isDevelopment = environment === Environment.DEVELOPMENT;
    
    this.updateConfig({
      baseURL: this.getBaseURL(environment),
      enableMock: isDevelopment,
      enableLogging: isDevelopment,
    });

    console.log(`🌍 [ApiConfig] 已配置为 ${environment} 环境`);
  }

  /**
   * 验证配置有效性
   */
  public validateConfig(): { isValid: boolean; errors: string[] } {
    const errors: string[] = [];
    const { config } = this;

    if (!config.baseURL) {
      errors.push('baseURL 不能为空');
    }

    if (config.timeout <= 0) {
      errors.push('timeout 必须大于0');
    }

    if (config.retryCount < 0) {
      errors.push('retryCount 不能为负数');
    }

    if (config.retryDelay < 0) {
      errors.push('retryDelay 不能为负数');
    }

    return {
      isValid: errors.length === 0,
      errors,
    };
  }

  /**
   * 获取环境信息
   */
  public getEnvironmentInfo(): {
    environment: Environment;
    isDevelopment: boolean;
    isProduction: boolean;
    baseURL: string;
  } {
    const environment = this.getCurrentEnvironment();
    
    return {
      environment,
      isDevelopment: environment === Environment.DEVELOPMENT,
      isProduction: environment === Environment.PRODUCTION,
      baseURL: this.config.baseURL,
    };
  }

  /**
   * 创建API URL
   */
  public createUrl(endpoint: string, params?: Record<string, any>): string {
    let url = `${this.config.baseURL}${endpoint}`;
    
    if (params) {
      const queryString = new URLSearchParams(params).toString();
      if (queryString) {
        url += `?${queryString}`;
      }
    }
    
    return url;
  }

  /**
   * 获取认证头信息
   */
  public getAuthHeaders(token?: string): Record<string, string> {
    const authToken = token || localStorage.getItem('access_token');
    
    if (!authToken) {
      return this.config.headers;
    }
    
    return {
      ...this.config.headers,
      Authorization: `Bearer ${authToken}`,
    };
  }

  /**
   * 重置为默认配置
   */
  public resetToDefaults(): void {
    this.config = this.getDefaultConfig();
    console.log('🔄 [ApiConfig] 已重置为默认配置');
  }

  /**
   * 导出配置用于调试
   */
  public exportForDebug(): {
    config: ApiConfig;
    endpoints: ApiEndpoints;
    environmentInfo: ReturnType<typeof this.getEnvironmentInfo>;
    validation: ReturnType<typeof this.validateConfig>;
  } {
    return {
      config: this.getConfig(),
      endpoints: this.getEndpoints(),
      environmentInfo: this.getEnvironmentInfo(),
      validation: this.validateConfig(),
    };
  }
}

/**
 * API服务工厂
 */
export class ApiServiceFactory {
  private static instance: ApiServiceFactory;
  private configManager: ApiConfigManager;

  private constructor() {
    this.configManager = ApiConfigManager.getInstance();
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): ApiServiceFactory {
    if (!ApiServiceFactory.instance) {
      ApiServiceFactory.instance = new ApiServiceFactory();
    }
    return ApiServiceFactory.instance;
  }

  /**
   * 创建商品服务
   */
  public createProductService() {
    const { ProductService } = require('./productService');
    const config = this.configManager.getConfig();
    const endpoints = this.configManager.getEndpoints();
    
    return new ProductService(config.baseURL + endpoints.products.base);
  }

  /**
   * 创建基础服务
   */
  public createBaseService(baseURL?: string) {
    const { BaseService } = require('./baseService');
    const config = this.configManager.getConfig();
    
    return new BaseService(baseURL || config.baseURL);
  }

  /**
   * 配置所有服务
   */
  public configureAllServices(): void {
    const environment = this.configManager.getCurrentEnvironment();
    this.configManager.configureForEnvironment(environment);
    
    console.log('🚀 [ApiServiceFactory] 所有服务已配置完成');
  }

  /**
   * 获取服务配置
   */
  public getServiceConfig() {
    return this.configManager.exportForDebug();
  }
}

// 导出单例实例
export const apiConfigManager = ApiConfigManager.getInstance();
export const apiServiceFactory = ApiServiceFactory.getInstance();

// 默认导出
export default ApiConfigManager;